package com.liu;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Yard  extends Frame {
    public static final int NodeSize =15; //每一小格的宽度,两条横线之间的间隔
    public static final int NodeCount =30;// 行数或者列数
    public static final  int AreaSize =NodeSize * NodeCount; //一行小格的长度，
    public static int x= AreaSize/2;  //网格的起始x轴坐标，水平向右,左上角起始位置为(0,0)
    public static  int y = AreaSize/2;//网格的起始y轴坐标, 竖直向下
    Egg e=new Egg(10,10);
    Snake s=new Snake();
    public static void main(String[] args){
        new Yard();
    }
        Yard(){
            this.setSize(2 * AreaSize,2*AreaSize);
            this.setVisible(true);
            this.addWindowFocusListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
            this.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) {
                    s.keyPressed(e);
                }
            });
            while(true){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.repaint();//窗口重画，

            }

        }
        public void paint(Graphics g){
            Color c= g.getColor();
            g.setColor(Color.WHITE);
            g.fillRect(0,0,this.getWidth(),this.getHeight());

            g.setColor(Color.BLACK);
            for(int i =0;i<=NodeCount;i++){ //画横线和竖线
                g.drawLine(x,y+NodeSize * i,x+AreaSize,y+NodeSize *i); //画横线, (x水平向右，y竖直向下)，{起始画笔位置x值不变, y=y + (间隔)NodeSize* i},
                // {末尾画笔的x值为: x+ 横线长度AreaSize, y 值为 y = y+ (间隔)NodeSize *i}
                g.drawLine(x+NodeSize*i,y,x+NodeSize*i,y+AreaSize); //画竖线，起始位置y值保持不变， x值为x+ (间隔)NodeSize *i,
                // 末尾画笔x为x + 间隔*i, 末尾画笔y为 y+ 竖线长度即 y+AreaSize


            }
            e.paint(g);
            s.paint(g);
            s.eat(e);
            g.setColor(c);
        }
// 双缓冲
        Image offScreenImage =null;
        public void update(Graphics g){
                if(offScreenImage==null){
                    offScreenImage = this.createImage(this.getWidth(),this.getHeight());
                }
                Graphics gOff =offScreenImage.getGraphics();
                paint(gOff);
                g.drawImage(offScreenImage,0,0,null);
        }

}




